<template>
  <div>
    <k-form-design ref="design" @close="onClose" @save="onSave"/>
  </div>
</template>
<script>
import { getById, save } from '@/api/formTemplate'
export default {
  name: 'TemplateDesigner',
  data() {
    return { saved: false }
  },
  mounted() {
    window.addEventListener('beforeunload', e => this.beforeunloadHandler(e))
  },
  destroyed() {
    window.removeEventListener('beforeunload', e => this.beforeunloadHandler(e))
  },
  created() {
    this.loadData()
  },
  methods: {
    beforeunloadHandler(e) {
      e = e || window.event
      if (this.saved) {
        return
      }
      // 兼容IE8和Firefox 4之前的版本
      if (e) {
        e.returnValue = '您是否确认离开此页面-您输入的数据可能不会被保存'
      }
      // Chrome, Safari, Firefox 4+, Opera 12+ , IE 9+
      return '您是否确认离开此页面-您输入的数据可能不会被保存'
    },
    onClose() {
      window.close()
    },
    loadData() {
      if (!this.$route.query.id) {
        return
      }
      getById({ id: this.$route.query.id }).then(({ data }) => {
        if (data) {
          const value = data.formData
          this.$refs['design'].handleSetData(value ? JSON.parse(value) : {})
        }
      })
    },
    onSave(data) {
      if (!this.$route.query.id) {
        return
      }
      save({ id: this.$route.query.id, formData: data }).then(res => {
        if (res.success) {
          this.$message.success('保存成功')
          this.saved = true
        }
      })
    }
  }
}
</script>
